#!/usr/bin/env python

from collections import deque
import sys

# code like grep -B 
# only run in python 3 because print function other that statement

def search(lines, pattern, history=5):
    previous_lines = deque(maxlen=history)
    for line in lines:
        if pattern in line:
            yield line, previous_lines
        previous_lines.append(line)
        
if __name__ == '__main__':
    arg_sz = len(sys.argv)
    if arg_sz < 2:
        print("Usage: " + sys.argv[0] + " filename pattern pnum", file=sys.stderr)
        exit(1)
    with open(sys.argv[1]) as f:
        for line, previous_lines in search(f, sys.argv[2], int(sys.argv[3])):
            for pline in previous_lines:
                print(pline, end='')
            print(line, end='')
            print('-' * 20)
